package com.demo.common.security.interceptor;

import com.demo.common.core.constants.SecurityConstants;
import com.demo.common.core.domain.LoginUser;
import com.demo.common.core.utils.ServletUtils;
import com.demo.common.core.context.SecurityContextHolder;
import com.demo.common.core.utils.SpringUtils;
import com.demo.common.core.utils.StringUtils;
import com.demo.common.redis.constants.CacheConstants;
import com.demo.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 *
 * @author wr
 */
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    RedisService redisService = SpringUtils.getBean(RedisService.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String userId = ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID);
        SecurityContextHolder.setUserId(userId);
        SecurityContextHolder.setAk(ServletUtils.getHeader(request, SecurityConstants.DETAILS_AK));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
        LoginUser loginUser = redisService.getCacheObject(CacheConstants.LOGIN_USER_KEY + userId);
        if (StringUtils.isNotNull(loginUser)) {
            SecurityContextHolder.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.remove();
    }
}
